//
//  DCIMRegisterViewController.m
//  xmppBase
//
//  Created by striby on 16/1/18.
//  Copyright © 2016年 com.dc. All rights reserved.
//

#import "DCIMRegisterViewController.h"
#import "RCUnderlineTextField.h"
#import "RCUnderlineTextField.h"
#import "SSCheckBoxView.h"
#import "MBProgressHUD.h"

@interface DCIMRegisterViewController ()

{
    UILabel * errorLbl;
    NSString * errorText;
    
    RCUnderlineTextField * account;
    RCUnderlineTextField * password;
    RCUnderlineTextField * rePassword;
    RCUnderlineTextField * emailAddress;
    RCUnderlineTextField * nickName;
    RCUnderlineTextField * telePhoneNum;
}

@property(nonatomic,strong)SSCheckBoxView * sexGril;
@property(nonatomic,strong)SSCheckBoxView * sexBoy;

@property(nonatomic,strong)RCAnimatedImagesView * animatedImagesView;

@property(nonatomic,strong)UIScrollView * contentScrollView;
@end


static const float leftLabelWidth=30;
static const float inputViewHeight = 40;
static const float viewMarin = 15;
static const int fontSize = 16;

@implementation DCIMRegisterViewController
@synthesize contentScrollView;


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    
    UIColor * color = [UIColor whiteColor];
    
    self.animatedImagesView = [[RCAnimatedImagesView alloc]
                               initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width,
                                                        self.view.bounds.size.height)];
    [self.view addSubview:self.animatedImagesView];
    self.animatedImagesView.delegate = self;
    
    UIButton * LoginBtn = [[UIButton alloc]initWithFrame:CGRectMake(DCDeviceWidth-80, 20, 60, 40)];
    [LoginBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [LoginBtn addTarget:self action:@selector(gotoLogin) forControlEvents:UIControlEventTouchUpInside];
    [LoginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [self.view addSubview:LoginBtn];
    
    
    errorLbl = [[UILabel alloc]initWithFrame:CGRectMake(20+leftLabelWidth, LoginBtn.frame.origin.y, 150, LoginBtn.frame.size.height)];
    errorLbl.textColor = [UIColor redColor];
    errorLbl.font = [UIFont systemFontOfSize:fontSize];
    errorLbl.text= @"";
    [self.view addSubview:errorLbl];
    
    
    contentScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(20, LoginBtn.frame.origin.y+LoginBtn.frame.size.height, DCDeviceWidth-40, DCDeviceHeight-(LoginBtn.frame.origin.y+LoginBtn.frame.size.height)-20)];
    
    contentScrollView.showsVerticalScrollIndicator=NO;
    [self.view addSubview:contentScrollView];
    
    
    
    UILabel * leftLabelaccount = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, leftLabelWidth, inputViewHeight)];
    leftLabelaccount.text = @"*";
    leftLabelaccount.textColor= [UIColor redColor];
    
    
    account = [[RCUnderlineTextField alloc]initWithFrame:CGRectMake(0, 0, contentScrollView.frame.size.width-leftLabelWidth, inputViewHeight)];
    account.borderStyle = UITextBorderStyleNone;
    account.returnKeyType= UIReturnKeyDone;
    account.font = [UIFont systemFontOfSize:fontSize];
    account.leftView = leftLabelaccount;
    account.leftViewMode = UITextFieldViewModeAlways;
    account.textColor = color;
    [account setValue:color forKeyPath:@"_placeholderLabel.textColor"];
    
    account.backgroundColor = [UIColor clearColor];
    account.borderStyle = UITextBorderStyleNone;
    account.attributedPlaceholder = [[NSAttributedString alloc]
                                           initWithString:@"账号"
                                           attributes:@{NSForegroundColorAttributeName : color}];

    [contentScrollView addSubview:account];
    
    
    UILabel * leftLabelpassword = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, leftLabelWidth, inputViewHeight)];
    leftLabelpassword.text = @"*";
    leftLabelpassword.textColor= [UIColor redColor];
    
    password = [[RCUnderlineTextField alloc]initWithFrame:CGRectMake(0,account.frame.origin.y+account.frame.size.height+viewMarin, contentScrollView.frame.size.width-leftLabelWidth, inputViewHeight)];
    password.borderStyle = UITextBorderStyleNone;
    password.returnKeyType= UIReturnKeyDone;
    password.secureTextEntry =YES;
     password.font = [UIFont systemFontOfSize:fontSize];
    password.leftView = leftLabelpassword;
    password.leftViewMode = UITextFieldViewModeAlways;
    password.textColor = color;
    [password setValue:color forKeyPath:@"_placeholderLabel.textColor"];
    
    password.backgroundColor = [UIColor clearColor];
    password.borderStyle = UITextBorderStyleNone;
    password.attributedPlaceholder = [[NSAttributedString alloc]
                                     initWithString:@"密码"
                                     attributes:@{NSForegroundColorAttributeName : color}];
    
    [contentScrollView addSubview:password];
    
    
    
    UILabel * leftLabelrePassword = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, leftLabelWidth, inputViewHeight)];
    leftLabelrePassword.text = @"*";
    leftLabelrePassword.textColor= [UIColor redColor];
    
    rePassword = [[RCUnderlineTextField alloc]initWithFrame:CGRectMake(0,password.frame.origin.y+password.frame.size.height+viewMarin, contentScrollView.frame.size.width-leftLabelWidth, inputViewHeight)];
    rePassword.borderStyle = UITextBorderStyleNone;
    rePassword.returnKeyType= UIReturnKeyDone;
    rePassword.secureTextEntry =YES;
    rePassword.font = [UIFont systemFontOfSize:fontSize];
    rePassword.leftView = leftLabelrePassword;
    rePassword.leftViewMode = UITextFieldViewModeAlways;
    rePassword.textColor = color;
    [rePassword setValue:color forKeyPath:@"_placeholderLabel.textColor"];
    
    rePassword.backgroundColor = [UIColor clearColor];
    rePassword.borderStyle = UITextBorderStyleNone;
    rePassword.attributedPlaceholder = [[NSAttributedString alloc]
                                      initWithString:@"验证密码"
                                      attributes:@{NSForegroundColorAttributeName : color}];
    
    [contentScrollView addSubview:rePassword];
    
    
    UILabel * leftLabelnickName = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, leftLabelWidth, inputViewHeight)];
    leftLabelnickName.text = @"*";
    leftLabelnickName.textColor= [UIColor redColor];
    
    nickName = [[RCUnderlineTextField alloc]initWithFrame:CGRectMake(0,rePassword.frame.origin.y+rePassword.frame.size.height+viewMarin, contentScrollView.frame.size.width-leftLabelWidth, inputViewHeight)];
    nickName.borderStyle = UITextBorderStyleNone;
    nickName.returnKeyType= UIReturnKeyDone;
    nickName.font = [UIFont systemFontOfSize:fontSize];
    nickName.leftView = leftLabelnickName;
    nickName.leftViewMode = UITextFieldViewModeAlways;
    nickName.textColor = color;
    [nickName setValue:color forKeyPath:@"_placeholderLabel.textColor"];
    
    nickName.backgroundColor = [UIColor clearColor];
    nickName.borderStyle = UITextBorderStyleNone;
    nickName.attributedPlaceholder = [[NSAttributedString alloc]
                                          initWithString:@"昵称"
                                          attributes:@{NSForegroundColorAttributeName : color}];
    
    [contentScrollView addSubview:nickName];

    

    UILabel * leftLabeltelePhoneNum = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, leftLabelWidth, inputViewHeight)];
    leftLabeltelePhoneNum.text = @"*";
    leftLabeltelePhoneNum.textColor= [UIColor redColor];
    
    telePhoneNum = [[RCUnderlineTextField alloc]initWithFrame:CGRectMake(0,nickName.frame.origin.y+nickName.frame.size.height+viewMarin, contentScrollView.frame.size.width-leftLabelWidth, inputViewHeight)];
    telePhoneNum.borderStyle = UITextBorderStyleNone;
    telePhoneNum.returnKeyType= UIReturnKeyDone;
    telePhoneNum.font = [UIFont systemFontOfSize:fontSize];
    telePhoneNum.leftView = leftLabeltelePhoneNum;
    telePhoneNum.leftViewMode = UITextFieldViewModeAlways;
    telePhoneNum.textColor = color;
    telePhoneNum.keyboardType = UIKeyboardTypePhonePad;
    [telePhoneNum setValue:color forKeyPath:@"_placeholderLabel.textColor"];
    
    telePhoneNum.backgroundColor = [UIColor clearColor];
    telePhoneNum.borderStyle = UITextBorderStyleNone;
    telePhoneNum.attributedPlaceholder = [[NSAttributedString alloc]
                                        initWithString:@"手机号码"
                                        attributes:@{NSForegroundColorAttributeName : color}];
    
    [contentScrollView addSubview:telePhoneNum];
    
    
    UILabel * leftLabelemailAddress = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, leftLabelWidth, inputViewHeight)];
    leftLabelemailAddress.text = @"";
    leftLabelemailAddress.textColor= [UIColor redColor];
    
    emailAddress = [[RCUnderlineTextField alloc]initWithFrame:CGRectMake(0,telePhoneNum.frame.origin.y+telePhoneNum.frame.size.height+viewMarin, contentScrollView.frame.size.width-leftLabelWidth, inputViewHeight)];
    emailAddress.borderStyle = UITextBorderStyleNone;
    emailAddress.returnKeyType= UIReturnKeyDone;
    emailAddress.font = [UIFont systemFontOfSize:fontSize];
    emailAddress.leftView = leftLabelemailAddress;
    emailAddress.leftViewMode = UITextFieldViewModeAlways;
    emailAddress.textColor = color;
    [emailAddress setValue:color forKeyPath:@"_placeholderLabel.textColor"];
    
    emailAddress.backgroundColor = [UIColor clearColor];
    emailAddress.borderStyle = UITextBorderStyleNone;
    emailAddress.attributedPlaceholder = [[NSAttributedString alloc]
                                          initWithString:@"邮箱地址"
                                          attributes:@{NSForegroundColorAttributeName : color}];
    
    [contentScrollView addSubview:emailAddress];

    
    
    /**
     女
     */
    _sexGril = [[SSCheckBoxView alloc]initWithFrame:CGRectMake(leftLabelWidth, emailAddress.frame.size.height+emailAddress.frame.origin.y+viewMarin, 60, 40) style:kSSCheckBoxViewStyleBox checked:NO];
    [_sexGril setStateChangedTarget:self selector:@selector(sexChanged:)];
    [_sexGril setText:@"女"];
    [_sexGril setTextColor:[UIColor whiteColor]];
    _sexGril.tag = DCGirl;
    _sexGril.translatesAutoresizingMaskIntoConstraints=NO;
    [contentScrollView addSubview:_sexGril];
    
    
    /**
     男
     */
    _sexBoy = [[SSCheckBoxView alloc]initWithFrame:CGRectMake(contentScrollView.frame.size.width - 50- leftLabelWidth, _sexGril.frame.origin.y, 60, 40) style:kSSCheckBoxViewStyleBox checked:NO];
    [_sexBoy setStateChangedTarget:self selector:@selector(sexChanged:)];
    [_sexBoy setText:@"男"];
    [_sexBoy setTextColor:[UIColor whiteColor]];
    _sexBoy.tag = DCBoy;
    _sexBoy.translatesAutoresizingMaskIntoConstraints=NO;
    [contentScrollView addSubview:_sexBoy];
    
    
    self.regAndLogin = [[UIButton alloc]initWithFrame:CGRectMake(leftLabelWidth, _sexGril.frame.origin.y+_sexGril.frame.size.height+viewMarin, DCDeviceWidth-3*leftLabelWidth, 45)];
    [self.regAndLogin setTitle:@"注册" forState:UIControlStateNormal];
    [self.regAndLogin setTitleColor:color forState:UIControlStateNormal];
    [self.regAndLogin setBackgroundImage:[UIImage imageNamed:@"login_button"] forState:UIControlStateNormal];
    
    
    
    [contentScrollView addSubview:self.regAndLogin];
    
    
    [self.regAndLogin addTarget:self action:@selector(regiserAndLogin) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    contentScrollView.contentSize = CGSizeMake(contentScrollView.bounds.size.width, self.regAndLogin.frame.origin.y+self.regAndLogin.frame.size.height+viewMarin);
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(UIKeyboardWillShowNotification:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(UIKeyboardWillHideNotification:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(registerFailed) name:kXmppRegiserFailed object:nil];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.animatedImagesView startAnimating];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    [self.animatedImagesView stopAnimating];
}

-(void)registerFailed
{
    errorLbl.text = @"用户已经注册";
}

#pragma mark - animationView
- (NSUInteger)animatedImagesNumberOfImages:
(RCAnimatedImagesView *)animatedImagesView {
    return 2;
}

- (UIImage *)animatedImagesView:(RCAnimatedImagesView *)animatedImagesView
                   imageAtIndex:(NSUInteger)index {
    return [UIImage imageNamed:@"animationBackground.jpg"];
    
}

#pragma mark - private method

-(void)regiserAndLogin
{
    
    BOOL result = [self chcekInfo];
    
    if (!result) {
        errorLbl.text = errorText;
    }
    else
    {
        errorLbl.text = @"";
    }
    
    
    NSMutableDictionary * userinfo =[[NSMutableDictionary alloc]init];
    
    [userinfo setObject:nickName.text forKey:kUserNickName];
    [userinfo setObject:telePhoneNum.text forKey:kUserTelephoneNum];
    
    if (emailAddress.text.length>0) {
        [userinfo setObject:emailAddress.text forKey:kUserEmail];
    }
    
    if (_sexBoy.checked||_sexGril.checked) {
        
        NSInteger i = _sexGril.checked==YES?_sexGril.tag:_sexBoy.tag;
        NSString * gender = [NSString stringWithFormat:@"%ld",(long)i];
        
        [userinfo setObject:gender forKey:kUserGender];
    }
    else
    {
        [userinfo setObject:[NSString stringWithFormat:@"%d",DCGenderUnknow] forKey:kUserGender];
    }
    
    [DCXMPPTool shareInstance].userinfo = userinfo;
    
    [[DCXMPPTool shareInstance] logoutXmppHost];
    
    
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    
    [defaults setObject:account.text forKey:kMyJID];
    [defaults setObject:password.text forKey:kPS];
    
    
    
    [DCXMPPTool shareInstance].connectionStatus=XmppConnectionStatusRegister;
    
    [[DCXMPPTool shareInstance] connectXmppHost];
}


-(BOOL)chcekInfo
{
    if (account.text.length<1) {
        errorText = @"请输入账号";
        return NO;
    }
    
    if (password.text.length<1) {
        errorText = @"请输入密码";
         return NO;
    }
    
    if (rePassword.text.length<1) {
        errorText = @"请输入验证密码";
        return NO;
    }
    
    
    if(![password.text isEqualToString:rePassword.text])
    {
        errorText = @"两次密码不一致";
        password.text = @"";
        rePassword.text = @"";
        return NO;
    }
    
    
    if (nickName.text.length<1) {
        errorText = @"请输入昵称";
        return NO;
    }
    
    if (telePhoneNum.text.length<1) {
        errorText = @"请输入手机号码";
        return NO;
    }
    

    
    if (![self validateMobile:telePhoneNum.text]) {
        errorText = @"手机号码错误";
        return NO;
    }
    
    if (emailAddress.text.length>0) {
        if (![self validateEmail:emailAddress.text]) {
            errorText = @"邮箱地址错误";
            return NO;
        }
    }
    
    
    
    
    return YES;
}

- (BOOL)validateMobile:(NSString *)mobileNum
{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189
     22         */
    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

- (BOOL) validateEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}


-(void)sexChanged:(SSCheckBoxView*)sender
{
    if(sender.tag==DCBoy)
    {
        _sexBoy.checked=YES;
        _sexGril.checked=NO;
    }
    else
    {
        _sexGril.checked=YES;
        _sexBoy.checked = NO;
    }
}


-(void)gotoLogin
{
    [self.navigationController popViewControllerAnimated:YES];
}



#pragma mark - 键盘
-(void)UIKeyboardWillShowNotification:(NSNotification*)noti
{
   
    CGRect  value =  [noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSNumber *duration = [noti.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
   
    [UIView animateWithDuration:duration.doubleValue animations:^{
      
        [contentScrollView setFrame:CGRectMake(contentScrollView.frame.origin.x, contentScrollView.frame.origin.y, contentScrollView.frame.size.width, DCDeviceHeight-contentScrollView.frame.origin.y-value.size.height)];
        
    }completion:^(BOOL finished) {
        
    } ];
}

-(void)UIKeyboardWillHideNotification:(NSNotification*)noti
{
    
  
    NSNumber *duration = [noti.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    
    [UIView animateWithDuration:duration.doubleValue animations:^{
        
        [contentScrollView setFrame:CGRectMake(contentScrollView.frame.origin.x, contentScrollView.frame.origin.y, contentScrollView.frame.size.width, DCDeviceHeight-contentScrollView.frame.origin.y-20)];
        
    }completion:^(BOOL finished) {
        
    } ];
}



@end
